package net.expectx.common.single.third.util;


import com.google.common.collect.Maps;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.util.AesUtil;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * <p>发送邮件工具类</p>
 * Created by lj on 2017-10-17.
 * @author lj
 */
public class EmailUtil {
    private static String mailHost;
    private static String mailTransportProtocol;
    private static Boolean mailSmtpAuth;
    private static String mailSmtpPort ;
    private static Boolean mailIsSSL;
    private static String mailSmtpSSLPort ;
    private static String mailSendFromAddress ;
    private static String mailSendFromAddressPassword ;

    /**
     *
     * @param host                  要连接的SMTP服务器
     * @param transportProtocol     要装入session的协议（smtp、pop3、imap、nntp）。
     * @param smtpAuth              缺省是false，如果为true，尝试使用AUTH命令认证用户。
     * @param smtpPort              要连接的SMTP服务器的端口号，如果connect没有指明端口号就使用它，缺省值25。
     * @param isSSL                 是否开启安全协议  默认false
     * @param smtpSSLPort           安全协议端口
     * @param username              SMTP的缺省用户名。
     * @param password              SMTP的缺省用户密码。  AesUtil.aesEncode(password)
     */
    public static void config(String host,String transportProtocol,Boolean smtpAuth,String smtpPort,Boolean isSSL,String smtpSSLPort,String username,String password) {
        mailHost=host;
        mailTransportProtocol=transportProtocol;
        mailSmtpAuth=smtpAuth;
        mailSmtpPort=smtpPort;
        mailSendFromAddress=username;
        mailSendFromAddressPassword=password;
        mailIsSSL=isSSL;
        mailSmtpSSLPort=smtpSSLPort;

    }
    private static  Session getSendEmailSession()throws Exception{
        mailSendFromAddressPassword= AesUtil.aesDecode(mailSendFromAddressPassword);
        Properties prop = new Properties();
        prop.setProperty("mail.host",mailHost);
        prop.setProperty("mail.transport.protocol", mailTransportProtocol);
        prop.setProperty("mail.smtp.auth",String.valueOf(mailSmtpAuth));
        if (mailIsSSL){
            prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            prop.put("mail.smtp.socketFactory.port", mailSmtpSSLPort);
            prop.put("mail.smtp.port",  mailSmtpPort);
        }else{
            prop.setProperty("mail.smtp.port", mailSmtpPort);
        }

        Session session = Session.getDefaultInstance(prop, new Authenticator(){
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailSendFromAddress,mailSendFromAddressPassword);
            }});
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);

        return  session;
    }
    public static BaseResult sendText(String toAddress, String subject, String content){
        Map resultMap= Maps.newHashMapWithExpectedSize(7);
        Boolean flag=false;
        String msg=null;
        try{
            Session session=getSendEmailSession();
            Transport ts = session.getTransport();
            ts.connect(mailHost, mailSendFromAddress,mailSendFromAddressPassword);
            Message message = createSimpleMail(session,toAddress,subject,content);
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
            System.out.println("--------------------发送邮件成功--------------------------");
            flag=true;
        }catch (Exception e){
            System.out.println("--------------------发送邮件错误："+e.getLocalizedMessage()+"--------------------------");
            e.printStackTrace();
            msg=e.getLocalizedMessage();
        }
        return  new BaseResult(flag,msg,null);
    }
    private static MimeMessage createSimpleMail(Session session,String toAddress,String subject,String content)
            throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailSendFromAddress));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
        message.setSubject(subject);
        message.setContent(content, "text/html;charset=UTF-8");
        return message;
    }
    public static void main(String[] args) throws Exception {
        config("smtp.163.com","smtp",true,"25",false,"465","li1991-hello@163.com", AesUtil.aesEncode("BA11C4B21AE2684B"));
        sendText("alfred@titifootball.com","2017.11.10意见反馈收集","<p>10意见反馈收集</p><span style='color:red'>10意见反馈收集</span>");

    }
}
